import webapp2
import cgi

import datamodel

class Dispatcher(webapp2.RequestHandler):
    sc = datamodel.ScoreBoard()
    def get(self):
        #self.response.headers['Content-Type'] = 'application/json'
        appkey = cgi.escape(self.request.get('appkey'))
        if len(appkey) == 0: 
            return    
        result = self.sc.getScore(appkey)
        if result:
            self.response.out.write(result)
        else:
            self.response.out.write("{error: \"in arguments\"}")
        return
    
    def post(self):
        appkey = cgi.escape(self.request.get('appkey')).strip()
        if not appkey:
            self.response.out.write("error in arguments")
            return

        username = cgi.escape(self.request.get('username')).strip()
        score = cgi.escape(self.request.get('score')).strip()

        if len(username) >0 and len(score) > 0  and score.isdigit():
            self.sc.submitScore(appkey, username, int(score))
            self.response.out.write("accepted")
        elif hasattr(self.request.body_file, 'read'):
            self.response.out.write(self.sc.hitTryNBuy(appkey, self.request.body))
          
